﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Framework.Common.Extention
{
    /// <summary>
    /// ReaderWriterLockSlimExtention
    /// </summary>
    public static class ReaderWriterLockSlimExtention
    {
        public static IDisposable ReadLock(this ReaderWriterLockSlim l)
        {
            l.EnterReadLock();
            return new ActionDisposable(l.ExitReadLock);
        }

        public static IDisposable UpgradableReadLock(this ReaderWriterLockSlim l)
        {
            l.EnterUpgradeableReadLock();
            return new ActionDisposable(l.ExitUpgradeableReadLock);
        }

        public static IDisposable WriteLock(this ReaderWriterLockSlim l)
        {
            l.EnterWriteLock();
            return new ActionDisposable(l.ExitWriteLock);
        }
    }

    /// <summary>
    /// 
    /// </summary>
    struct ActionDisposable : IDisposable
    {
        readonly Action _action;
        /// <summary>
        /// ActionDisposable
        /// </summary>
        /// <param name="action"></param>
        public ActionDisposable(Action action)
        {
            this._action = action;
        }

        #region IDisposable Members
        /// <summary>
        /// Dispose
        /// </summary>
        public void Dispose()
        {
            _action();
        }

        #endregion
    }
}
